package com.ikas.ai.server.error;

import com.ikas.ai.consts.Consts;
import com.ikas.ai.handle.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.URLEncoder;

@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        String uri = request.getRequestURI();
        if (e.getClass().isAssignableFrom(org.apache.catalina.connector.ClientAbortException.class)) {
            return null;
        }
        logger.error(String.format("GlobalExceptionResolver catch exception %s, %s", uri, e.getMessage()), e);
        JsonResult result = new JsonResult();
        if (o instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) o;
            ResponseBody rb = method.getMethodAnnotation(ResponseBody.class);
            if (rb != null) {
                try {
                    if (e.getMessage().contains("<")) {
                        result.setMessage(URLEncoder.encode(e.getMessage(), "UTF-8"));
                    } else {
                        result.setMessage(e.getMessage());
                    }
                } catch (Exception e1) {
                    logger.error(String.format("URLEncoder.encode error %s", e.getMessage()));
                }
            }
        }
        PrintWriter writer = null;
        response.setCharacterEncoding(Consts.CHART_SET);
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            result.setRemark("GlobalExceptionResolver");
            writer.print(result.toJSON());
        } catch (Exception th) {
            logger.error("GlobalExceptionResolver.resolveException print json throw exception.", th);
        } finally {
            if (writer != null) {
                writer.close();
            }
            response.setStatus(HttpServletResponse.SC_OK);
            e = null;
        }
        return null;
    }

}
